<?php

namespace App\Http\Controllers\Chat\Api;

use App\Http\Controllers\Chat\BaseController;
use App\Models\Api\User;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\Request;

class LoginController extends BaseController
{
    public function index(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->all();
        try {
            if(empty($data['user_name'])) {
                return ApiResponseTrait::error('请输入用户名');
            }
            if(empty($data['password'])) {
                return ApiResponseTrait::error('请输入密码');
            }

            $userInfo = User::whereUserName($data['user_name'])->whereStatus(User::STATUS_ON)->first();
            if(empty($userInfo->id)){
                return ApiResponseTrait::error('用户信息不存在');
            }

            if(false === password_verify($data['password'], $userInfo->password)) {
                return ApiResponseTrait::error('登录密码错误');
            }

            $token = User::setToken($userInfo);

            return ApiResponseTrait::success(['access_token' => $token],'用户登录成功');
        } catch (\Exception $exception) {
            return ApiResponseTrait::error($exception->getMessage());
        }
    }

    public function userInfo(Request $request): \Illuminate\Http\JsonResponse
    {
        $token = $request->input('access_token');
        if(empty($token)) {
            return ApiResponseTrait::error('非法请求');
        }
        $userInfo = (new User)->getUser($token);
        if(empty($userInfo['id'])) {
            return ApiResponseTrait::error('用户信息不存在');
        }

        return ApiResponseTrait::success($userInfo);
    }

    public function logout(Request $request): \Illuminate\Http\JsonResponse
    {
        $token = $request->input('access_token');
        if(empty($token)) {
            return ApiResponseTrait::error('非法请求');
        }
        $userInfo = User::whereLastLoginToken($token)->first();
        if(empty($userInfo->id)) {
            return ApiResponseTrait::error('用户信息不存在');
        }

        $userInfo->last_login_token = '';
        if($userInfo->save() === false || $this->delUser($token) === false || $this->delSocket($userInfo->id) === false) {
            return ApiResponseTrait::error('退出登录失败');
        }

        return ApiResponseTrait::success([], '退出登录成功');
    }
}
